<template>
  <div class="login-container" @touchmove="handleTouchMove">

    <div class="login-img">
      <img :src="logoImg" alt="" />
    </div>

    <div class="login-form" :style="loginFormStyle">
      <div class="login-title">
        <img :src="cspTitle" alt="" />
      </div>

      <div class="card-content">
        <van-form @submit="onSubmit">
          <van-cell-group inset>

            <van-field v-model="username" placeholder="请输入用户名" :rules="[{ required: true, message: '请输入用户名' }]"
              class="name-class name-position" ref="usernameRef">
              <template #left-icon>
                <div class="name-top-icon">
                  <van-icon name="contact" size="15px" />
                </div>
              </template>
            </van-field>

            <van-field v-model="password" type="password" placeholder="请输入密码"
              :rules="[{ required: true, message: '请输入密码' }]" class="name-position" ref="passwordRef">
              <template #left-icon>
                <div class="name-top-icon">
                  <van-icon name="bag-o" size="17px" />
                </div>
              </template>
            </van-field>
          </van-cell-group>
          <div style="margin: 16px;">
            <van-button block type="primary" native-type="submit" color="#bf1920">
              登录{{ loading ? '&nbsp;中...' : '' }}
            </van-button>
          </div>
        </van-form>

        <div class="issue" @click="common">
          <span class="common-issue">常见问题</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, onBeforeUnmount, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import logoImg from '@/assets/svg/logo.svg'
import { getUserLogin } from '@/api/login';
import { useUserStore } from "@/stores/user";
import cspTitle from '@/assets/image/csp-title.png'
import { useKeyboard, isKeyboardOpen } from '@/utils/keyboard'

// 用户名和密码输入框引用
const usernameRef = ref<HTMLInputElement | null>(null)
const passwordRef = ref<HTMLInputElement | null>(null)

// 键盘状态响应式变量
const keyboardVisible = ref(false)

// 键盘处理对象 - 使用inputRefs参数处理多个输入框
const keyboard = useKeyboard({
  inputRefs: [usernameRef, passwordRef],
  autoRegister: true,
  hideOnScroll: true
})

// 监听键盘状态变化
watch(isKeyboardOpen, (newValue) => {
  keyboardVisible.value = newValue
})

// 在页面滚动时手动关闭键盘
const handleScroll = () => {
  if (keyboardVisible.value) {
    keyboard.hideKeyboard()
  }
}

// 监听页面滚动
onMounted(() => {
  window.addEventListener('scroll', handleScroll, { passive: true })
  document.addEventListener('scroll', handleScroll, { passive: true })
})

// 清理事件监听
onBeforeUnmount(() => {
  window.removeEventListener('scroll', handleScroll)
  document.removeEventListener('scroll', handleScroll)
})

// 计算登录表单的样式
const loginFormStyle = computed(() => {
  // 基础样式
  const style: any = {
    paddingTop: isSafari.value ? '150px' : '60px'
  }
  return style
})

const store = useUserStore();

const router = useRouter()

const route = useRoute()

const username = ref('');

const password = ref('');

const loading = ref(false)

const isSafari = ref(false)

//登录
const onSubmit = async () => {
  try {

    loading.value = true

    const res = await getUserLogin({ username: username.value, password: password.value })

    if (res.statusCode === 200) {
      if (res.data.is_verify === 1) {
        store.userName = username.value

        store.passWord = password.value

        router.push({ path: '/check', query: { type: '1' } })
      } else {

        await store.getReading(true, username.value)

        if (!store.readShow) {
          store.userName = username.value

          store.passWord = password.value

          router.push({ path: '/confirm-dialog' })
        } else {
          await store.getLogin({ username: username.value, password: password.value })

          const redirect = route.query.redirect as string

          router.push({
            path: redirect || '/menu/worksheets'
          })

          store.getPermission()
        }
      }
    }

  } catch (error) {
    //
  } finally {
    loading.value = false
  }
}

//常见问题跳转
const common = () => {
  window.location.href = `${import.meta.env.BASE_URL}static/common/faq.html`;
  // userConfig.base + '/static/common/faq.html'
  // window.open('/mobile/static/common/faq.html');
}

// 处理触摸移动事件
const handleTouchMove = () => {
  // 如果键盘是打开的，则尝试关闭它
  if (keyboardVisible.value) {
    keyboard.hideKeyboard()
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  width: 100%;
  height: 100vh;
  background-image: url('@/assets/image/bg-lightgray.png');
  background-size: cover;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch; /* 启用iOS平滑滚动 */
  overscroll-behavior: none; /* 防止橡皮筋效果 */
  position: relative; /* 确保定位上下文 */
  
  /* 防止iOS Safari的橡皮筋效果 */
  &::before {
    content: "";
    position: absolute;
    width: 100%;
    height: 1px;
    background: transparent;
    top: -1px;
  }
  
  &::after {
    content: "";
    position: absolute;
    width: 100%;
    height: 1px;
    background: transparent;
    bottom: -1px;
  }

  .login-img {
    width: 100%;
    height: 50px;
    background: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;

    img {
      height: 32px;
      margin-left: 10px;
    }
  }

  .login-form {
    flex: 1;
    display: flex;
    flex-direction: column;
    // justify-content: center;
    align-items: center;
    // padding-top: 100px;

    .login-title {
      margin-bottom: 15px;

      img {
        width: 280px;
      }
    }

    .card-content {
      width: 330px;
      padding: 5px 5px 0;
      background: #fff;
      box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
      border-radius: 4px;

      .name-class {
        margin-top: 10px;
      }

      .name-position {
        position: relative;
        height: 56px;

        .name-top-icon {
          position: absolute;
          top: 14px;
          left: 32px;
        }
      }

      .issue {
        width: 100%;
        display: flex;
        justify-content: end;
        margin-left: auto;
        text-decoration: underline;
        color: #255ef8;
        padding-bottom: 10px;
        cursor: pointer;

        .common-issue {
          display: inline-block;
          padding-right: 20px;
        }
      }

      :deep(.van-form) {
        .van-cell-group {

          .van-cell {

            .van-field__value {
              border: 1px solid #dcdfe6;
              height: 32px;
              padding-top: 4px;
              box-sizing: border-box;

              .van-field__body {

                .van-field__control {
                  padding-left: 30px;
                  font-size: 12px;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
